<template>
    <div class="user-form-dialog">
        <el-dialog
            :title="title"
            v-model="dialogVisible"
            width="40%"
            :destroy-on-close="true"
            :close-on-click-modal="false"
        >
            <el-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
            >                <el-form-item :label="t('user.loginName')" prop="login_Name">
                    <el-input v-model="formData.login_Name" :placeholder="t('user.pleaseEnterLoginName')" />
                </el-form-item>
                <el-form-item :label="t('user.name')" prop="name">
                    <el-input v-model="formData.name" :placeholder="t('user.pleaseEnterName')" />
                </el-form-item>
                <el-form-item v-if="operate === 'add'" :label="t('user.password')" prop="password">
                    <el-input
                        v-model="formData.password"
                        :placeholder="t('user.pleaseEnterPassword')"
                        show-password
                    />
                </el-form-item>
                <el-form-item :label="t('user.email')" prop="email">
                    <el-input v-model="formData.email" :placeholder="t('user.pleaseEnterEmail')" />
                </el-form-item>
                <el-form-item :label="t('user.phone')" prop="phone">
                    <el-input v-model="formData.phone" :placeholder="t('user.pleaseEnterPhone')" />
                </el-form-item>                <el-form-item :label="t('user.avatar')">
                    <div class="avatar-uploader">
                        <el-avatar
                            v-if="formData.avatar"
                            :size="80"
                            :src="formData.avatar"
                            class="avatar-preview"
                        />
                        <el-upload
                            class="avatar-uploader-box"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload"
                            :http-request="uploadAvatar"
                        >
                            <el-button type="primary" :icon="'el-icon-Upload'">
                                {{ formData.avatar ? t('user.changeAvatar') : t('user.uploadAvatar') }}
                            </el-button>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item :label="t('user.dept')" prop="dept">
                    <el-input v-model="formData.dept" :placeholder="t('user.pleaseEnterDept')" />
                </el-form-item>
                <el-form-item :label="t('user.company')" prop="company">
                    <el-input v-model="formData.company" :placeholder="t('user.pleaseEnterCompany')" />
                </el-form-item>
                <el-form-item :label="t('user.remark')">
                    <el-input
                        v-model="formData.remark"
                        type="textarea"
                        :rows="3"
                        :placeholder="t('user.pleaseEnterRemark')"
                    />
                </el-form-item>                <el-form-item :label="t('user.status')">
                    <el-switch
                        v-model="formData.is_Enable"
                        :active-value="1"
                        :inactive-value="0"
                        :disabled="isCurrentLoginUser"
                    />
                    <span class="ml-2">{{ parseInt(formData.is_Enable) === 1 ? t('user.enabled') : t('user.disabled') }}</span>
                    <el-tag v-if="isCurrentLoginUser" type="warning" size="small" class="ml-2">{{ t('user.currentUser') }}</el-tag>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">{{ t('user.cancel') }}</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">
                        {{ t('user.confirm') }}
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import userApi from '/@/api/backendManage/auth/user'
import type { FormInstance } from 'element-plus'
import { useAdminInfo } from '/@/stores/adminInfo' // 导入当前用户信息

const { t } = useI18n()
const baTable: any = inject('baTable')
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()
const adminInfo = useAdminInfo() // 使用当前登录用户信息
const formData = reactive<Record<string, any>>({
    id: 0,
    login_Name: '',
    name: '',
    password: '',
    email: '',
    phone: '',
    avatar: '',
    remark: '',
    dept: '',
    company: '',
    is_Enable: 1,
    version: 0,
})
const operate = ref('')
const isCurrentLoginUser = ref(false) // 添加当前用户标识

// 表单验证规则
const rules = {
    login_Name: [
        { required: true, message: t('user.pleaseEnterLoginName'), trigger: 'blur' },
        { min: 3, max: 20, message: t('user.loginNameLengthLimit'), trigger: 'blur' }
    ],
    name: [
        { required: true, message: t('user.pleaseEnterName'), trigger: 'blur' }
    ],
    password: [
        { required: true, message: t('user.pleaseEnterPassword'), trigger: 'blur' },
        { min: 6, max: 30, message: t('user.passwordLengthLimit'), trigger: 'blur' }
    ],
    email: [
        { type: 'email', message: t('user.emailFormatError'), trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: t('user.phoneFormatError'), trigger: 'blur' }
    ]
}

// 计算标题
const title = computed(() => {
    return operate.value === 'add' ? '新增用户' : '编辑用户'
})

// 打开表单对话框
const open = (type: string) => {
    operate.value = type
    
    // 初始化表单数据
    if (type === 'add') {
        Object.keys(formData).forEach(key => {
            if (key === 'is_Enable') {
                formData[key] = 1
            } else if (key === 'version' || key === 'id') {
                formData[key] = 0
            } else {
                formData[key] = ''
            }
        })
        isCurrentLoginUser.value = false // 新增用户不是当前登录用户
    } else {
        // 编辑时从baTable.state.form.items中获取数据
        Object.keys(formData).forEach(key => {
            // 将is_Enable转换为数字类型
            if (key === 'is_Enable' && baTable.state.form.items[key] !== undefined) {
                formData[key] = parseInt(baTable.state.form.items[key])
            } else {
                formData[key] = baTable.state.form.items[key] || ''
            }
        })
        
        // 检查是否为当前登录用户
        isCurrentLoginUser.value = parseInt(formData.id) === parseInt(adminInfo.id)
    }
    
    dialogVisible.value = true
}

// 提交表单
const submitForm = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            // 检查是否是当前登录用户并且尝试禁用
            if (isCurrentLoginUser.value && parseInt(formData.is_Enable) === 0) {
                ElMessage.warning(t('user.cannotDisableCurrentUser') || '不能禁用当前登录用户')
                formData.is_Enable = 1 // 强制设为启用状态
                return
            }
            
            submitLoading.value = true
            
            // 准备提交的数据
            const submitData = {
                ...formData
            }
            
            // 如果是编辑模式且没修改密码，则删除password字段
            if (operate.value === 'edit' && !submitData.password) {
                delete submitData.password
            }            // 调用 userApi 的保存方法
            userApi.saveUser(submitData)
                .then(() => {
                    dialogVisible.value = false
                    // 发射更新事件让父组件刷新列表
                    const event = new CustomEvent('user.update')
                    window.dispatchEvent(event)
                })
                .finally(() => {
                    submitLoading.value = false
                })
        } else {
            return false
        }
    })
}

// 头像上传前的验证
const beforeAvatarUpload = (file: any) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error(t('user.avatarFormatLimit'))
        return false
    }
    if (!isLt2M) {
        ElMessage.error(t('user.avatarSizeLimit'))
        return false
    }
    return true
}

// 上传头像
const uploadAvatar = (options: any) => {
    // 使用封装的API上传头像
    userApi.uploadAvatar(options.file)
        .then(res => {
            if (res.data && res.data.url) {
                // 更新表单数据中的头像地址
                formData.avatar = res.data.url
                ElMessage.success(t('user.uploadSuccess'))
            }
        }).catch(() => {
            ElMessage.error(t('user.uploadFail'))
        })
}

// 暴露方法给父组件调用
defineExpose({
    open
})
</script>

<style lang="scss" scoped>
.user-form-dialog {
    :deep(.el-dialog__body) {
        padding-top: 10px;
        padding-bottom: 10px;
    }
    
    .avatar-uploader {
        display: flex;
        align-items: center;
        
        .avatar-preview {
            margin-right: 20px;
            border: 1px solid var(--el-border-color);
        }
    }
    
    /* 添加当前用户标签样式 */
    .ml-2 {
        margin-left: 8px;
    }
}
</style>
